//
//  TypeBuilder
//
//  Created by Caue W. on 2011-03-11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//
package time;
import time.types.ds.Key;

typedef NotNull<T> = T;
typedef Text = String;
typedef Varchar<Const> = String;
typedef BigInt = time.types.complex.BigInt;
typedef Wrap<T> = T;

import haxe.io.Bytes;
typedef Blob = Bytes;
typedef VarBlob<Const> = Bytes;

@Entity @ValueType class Time
{
	private var time:Int;
	
	@Transient var str:String;
	
	public function new(hours, minutes, seconds, ms, ?negative:Bool = false) : Void
	{
		if (hours < 0 || minutes < 0 || seconds < 0 || ms < 0)
			throw "Illogical time: If negative, use negative flag";
		
		this.time = ms + (seconds * 1000) + (minutes * 60000) + (hours * 3600000);
		if (this.time < 0)
			throw "Time too big (overflow) :" + hours + " : " + minutes + " : " + seconds + " . " + ms;
			
		if (negative)
			time = -time;
	}
	
	public static function delta(d1:Date, d2:Date) : Time
	{
		var delta = Std.int(d1.getTime() - d2.getTime());
		var t = new Time(0,0,0,0);
		t.time = delta;
		
		return t;
	}
	
	
	public inline function hours() : Int
	{
		return Std.int(time / 3600000);
	}
	
	public inline function minutes() : Int
	{
		return Std.int(time / 60000) % 60;
	}
	
	public inline function seconds() : Int
	{
		return Std.int(time / 1000) % 60;
	}
	
	public inline function ms() : Int
	{
		return time % 1000;
	}
	
	public inline function rawMs() : Int
	{
		return time;
	}
	
	public function toString() : String
	{
		if (str != null)
			return str;
		
		var ms_str = ms() + "";
		while (ms_str.length < 3)
			ms_str += "0";
		
		return str = format(hours()) + ":" + format(minutes()) + ":" + format(seconds()) + "." + ms_str;
	}
	
	inline function format(i:Int) : String
	{
		if (i < 10)
			return "0" + i;
		else
			return i + "";
	}
}